//
//  LoginController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/10/1.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "LoginController.h"
#import <JPUSHService.h>
#import "CreateAccountController.h"
#import "MaintainViewController.h"

#define POST_BOUNDS @"9"
@interface LoginController ()<UITextFieldDelegate>
@property (nonatomic,strong) UITextField *phoneTF;
@property (nonatomic,strong) UITextField *codeTF;
@property (nonatomic,strong) UIButton *codeBtn;
@property (nonatomic,strong) UIButton *loginBtn;
@property (nonatomic,assign) BOOL isSelect;
@end

@implementation LoginController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createUIView];
//    [self changeShopState];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TextFieldChange) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)createUIView
{
    self.view.backgroundColor = TotalWhite;
    self.bgNavView.hidden = YES;
    UIView *navi = [UIView new];
    if (@available(iOS 11.0, *)) {
        navi.frame = CGRectMake(0, 0, SCREENWIDTH, TopBarHeight_xs);
    } else {
        // Fallback on earlier versions
        navi.frame = CGRectMake(0, 0, SCREENWIDTH, TopBarHeight);
    }
    navi.backgroundColor = TotalWhite;
    [self.view addSubview:navi];
    
    UILabel *titleLab = [UILabel new];
    titleLab.frame = CGRectMake(40, navi.bottom+40, 79, 50);
    titleLab.attributedText = [TTKUtil getAtttributeStringWithLineSpace:0 kern:3 and:@"登录"];
    titleLab.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:36];
    titleLab.textColor = UIColorFromHex(0x4D4D4D);
    //titleLab.text = @"登录";
    [self.view addSubview:titleLab];
    
    UILabel *phoneLab = [UILabel new];
    phoneLab.frame = CGRectMake(2*leftPadding, titleLab.bottom+55, 55, 12);
    phoneLab.attributedText = [TTKUtil getAtttributeStringWithLineSpace:0 kern:1 and:@"手机号码"];
    phoneLab.textColor = goldColor;
    phoneLab.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:12];
    [self.view addSubview:phoneLab];
    
    self.phoneTF = [UITextField new];
    self.phoneTF.frame = CGRectMake(phoneLab.left, phoneLab.bottom+10, SCREENWIDTH-80, 16);
    self.phoneTF.delegate = self;
    //self.phoneTF.secureTextEntry = YES;
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    UIButton *button = [self.phoneTF valueForKey:@"_clearButton"];
    [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
    self.phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.phoneTF.placeholder = @"请输入手机号码";
     [self.phoneTF setValue:UIColorFromHex(0xD8D8D8) forKeyPath:@"_placeholderLabel.textColor"];
    [self.phoneTF setValue:FontWithSize(16) forKeyPath:@"_placeholderLabel.font"];
    self.phoneTF.returnKeyType = UIReturnKeyNext;
    self.phoneTF.textColor = titleColor;
    self.phoneTF.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    [self.view addSubview:self.phoneTF];
    
    UIView *lineView = [UIView new];
    lineView.frame = CGRectMake(phoneLab.left, _phoneTF.bottom+10, SCREENWIDTH-80, 1);
    lineView.backgroundColor = BacklineColor;
    [self.view addSubview:lineView];
    
    UILabel *codeLab = [UILabel new];
    codeLab.frame = CGRectMake(2*leftPadding, lineView.bottom+20, 55, 12);
    codeLab.attributedText = [TTKUtil getAtttributeStringWithLineSpace:0 kern:1 and:@"验证码"];
    codeLab.textColor = goldColor;
    codeLab.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:12];
    [self.view addSubview:codeLab];
    
    self.codeTF = [UITextField new];
    self.codeTF.frame = CGRectMake(phoneLab.left, codeLab.bottom+10, (SCREENWIDTH-80)*0.6, 16);
    self.codeTF.delegate = self;
    self.codeTF.keyboardType = UIKeyboardTypeNumberPad;
    self.codeTF.returnKeyType = UIReturnKeyDone;
    self.codeTF.textColor = titleColor;
    self.codeTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.codeTF.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
    self.codeTF.placeholder = @"请输入手机验证码";
    [self.codeTF setValue:UIColorFromHex(0xD8D8D8) forKeyPath:@"_placeholderLabel.textColor"];
    [self.codeTF setValue:FontWithSize(16) forKeyPath:@"_placeholderLabel.font"];
    [self.view addSubview:self.codeTF];
    
    UIView *mid = [UIView new];
    mid.frame = CGRectMake(self.codeTF.right, self.codeTF.top+3, 1, 10);
    mid.backgroundColor = BacklineColor;
    [self.view addSubview:mid];
    
    self.codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat wid = (SCREENWIDTH-80)*0.42;
    self.codeBtn.frame = CGRectMake(mid.right+15, self.codeTF.top, wid-16, 16);
    [self.codeBtn setAttributedTitle:[TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.33 and:@"发送验证码"] forState:UIControlStateNormal];
    self.codeBtn.titleLabel.font = FontWithSize(16);
    [self.codeBtn addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.codeBtn];
    
    UIView *MidlineView = [UIView new];
    MidlineView.frame = CGRectMake(phoneLab.left, self.codeTF.bottom+10, SCREENWIDTH-80, 1);
    MidlineView.backgroundColor = BacklineColor;
    [self.view addSubview:MidlineView];
    
    self.loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginBtn.frame = CGRectMake(2*leftPadding, MidlineView.bottom+90, SCREENWIDTH-80, 50);
    [self.loginBtn setAttributedTitle:[TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.5 and:@"登录"] forState:UIControlStateNormal];
    self.loginBtn.layer.cornerRadius = 25;
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.backgroundColor = UIColorFromHex(0xD1D1D1);
    self.loginBtn.titleLabel.font = FontWithSize(18);
    [self.loginBtn setTitleColor:UIColorFromHex(0x8D8D8D) forState:UIControlStateNormal];
    [self.loginBtn addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    
    UIButton *protocBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat left = (SCREENWIDTH-110)/2;
    protocBtn.frame = CGRectMake(left, self.loginBtn.bottom+15, 11, 11);
    protocBtn.selected = YES;
    self.isSelect = YES;
    protocBtn.layer.borderWidth = 1;
    protocBtn.layer.borderColor = UIColorFromHex(0x62616).CGColor;
    protocBtn.backgroundColor = goldColor;
    [protocBtn addTarget:self action:@selector(proBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:protocBtn];
    
    //设置可点击的textview
    ClickTextView *clickTV = [[ClickTextView alloc]initWithFrame:CGRectMake(protocBtn.right+10, self.loginBtn.bottom+7, 100, 25)];
    clickTV.backgroundColor = TotalWhite;
    clickTV.textColor = UIColorFromHex(0x999999);
    clickTV.font = FontMediumWithSize(14);
    NSString *content = @"同意<用户协议>";
    clickTV.text = content;
    NSRange range1 = [content rangeOfString:@"用户协议"];
    [clickTV setUnderLineTextViewWithRange:range1 withUnderLineColor:goldColor andWithCoverColor:nil withBlock:^(NSString *text) {
        WebViewController *webVC = [WebViewController new];
        webVC.urlString = @"http://serv.eb56.com/html/registration-agreement.html";
        webVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:webVC animated:YES];
    }];
    [self.view addSubview:clickTV];
    
//    UILabel *proLab = [UILabel new];
//    proLab.frame = CGRectMake(protocBtn.right+5, self.loginBtn.bottom+20, 94, 17);
//    proLab.attributedText = [TTKUtil getAtttributeStringWithLineSpace:0 kern:0.86 and:@"同意<用户协议>"];
//    proLab.textColor = UIColorFromHex(0x343434);
//    proLab.font = FontWithSize(12);
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(proLabTap:)];
//    [proLab addGestureRecognizer:tap];
//    [self.view addSubview:proLab];
    /*
    //微信登录
    UIImageView *wechatIV = [UIImageView new];
    CGFloat leftPadd = (SCREENWIDTH-35)/2;
    wechatIV.frame = CGRectMake(leftPadd, clickTV.bottom+69, 35, 35);
    wechatIV.image = [UIImage imageNamed:@"wechat"];
    [self.view addSubview:wechatIV];
    
    UILabel *wechatLab = [UILabel new];
    CGFloat leftPaddLab = (SCREENWIDTH-53)/2;
    wechatLab.frame = CGRectMake(leftPaddLab, wechatIV.bottom+10, 53, 12);
    wechatLab.attributedText = [TTKUtil getAtttributeStringWithLineSpace:0 kern:1 and:@"微信登录"];
    wechatLab.textColor = UIColorFromHex(0xB7B7B7);
    wechatLab.font = FontWithSize(12);
    [self.view addSubview:wechatLab];
    
    UIButton *wechatBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    wechatBtn.frame = CGRectMake(leftPaddLab, wechatIV.top, 53, 57);
    wechatBtn.backgroundColor = ClearColor;
    [wechatBtn addTarget:self action:@selector(wechatBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:wechatBtn];
     */
}


#pragma mark -- 协议点击
- (void)proBtn:(UIButton *)btn
{
    btn.selected = !btn.selected;
//    self.isSelect=YES?btn.backgroundColor= UIColorFromHex(0xEFD053): TotalWhite;
    if (btn.selected) {
        btn.backgroundColor = goldColor;
    }else
    {
        btn.backgroundColor = TotalWhite;
    }
}

- (void)proLabTap:(UITapGestureRecognizer *)tap
{
    NSLog(@"tap");
}

- (void)TextFieldChange
{
    NSString *phone = self.phoneTF.text;
    NSString *code = self.codeTF.text;
    if (phone.length > 11) {
        phone = [phone substringToIndex:11];
    }
    if (code.length > 6) {
        code = [code substringToIndex:6];
    }
    if (phone.length>0) {
        self.phoneTF.attributedText = [TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.33 and:phone];
        self.phoneTF.textColor = titleColor;
    }
    if (code.length>0) {
        self.codeTF.attributedText = [TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.33 and:code];
        self.codeTF.textColor = titleColor;
    }
    if (phone.length == 11 && code.length == 6) {
        self.loginBtn.userInteractionEnabled = YES;
        self.loginBtn.backgroundColor = goldColor;
        self.loginBtn.titleLabel.textColor = titleColor;
    }else
    {
        self.loginBtn.userInteractionEnabled = NO;
        self.loginBtn.backgroundColor = UIColorFromHex(0xD1D1D1);
        self.loginBtn.titleLabel.textColor = UIColorFromHex(0x8D8D8D);
    }
}

#pragma mark -- 验证码点击
-(void)getCode:(UIButton *)btn
{
    NSString *phone = self.phoneTF.text;
    if([phone isEqualToString:@""])
    {
        [TTKUtil hudShowMessage:@"请输入手机号码"];
        return;
    }
     if (![TTKStringUtils isValidateMobile:phone])
     {
          [TTKUtil hudShowMessage:@"请输入正确的手机号码"];
         return;
     }
   
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setValue:self.phoneTF.text forKey:@"mobile"];
    [HttpRequest formPostPath:GetVerifyCode_API params:data resultBlock:^(id Data, MsgModel *msgModel) {
        [self ShowHUDWithMessage:@"验证码发送成功"];
    }];
        
    [self startCodeBtnTimeWithBtn:btn];
}

- (NSDictionary *)postUrl:(NSString *)myUrl and:(NSMutableDictionary*)dicData
{
    NSURL *url = [NSURL URLWithString:myUrl];
    NSMutableString *bodyContent = [NSMutableString string];
    for(NSString *key in dicData.allKeys){
        id value = [dicData objectForKey:key];
        [bodyContent appendFormat:@"--%@\r\n",POST_BOUNDS];
        [bodyContent appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        [bodyContent appendFormat:@"%@\r\n",value];
    }
    [bodyContent appendFormat:@"--%@--\r\n",POST_BOUNDS];
    NSData *bodyData=[bodyContent dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    [request addValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",POST_BOUNDS] forHTTPHeaderField:@"Content-Type"];
    [request addValue: [NSString stringWithFormat:@"%zd",bodyData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:bodyData];
    NSLog(@"请求的长度%@",[NSString stringWithFormat:@"%zd",bodyData.length]);
    __autoreleasing NSError *error=nil;
    __autoreleasing NSURLResponse *response=nil;
    NSLog(@"输出Bdoy中的内容>>\n%@",[[NSString alloc]initWithData:bodyData encoding:NSUTF8StringEncoding]);
    NSData *reciveData= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSDictionary *data = [NSJSONSerialization JSONObjectWithData:reciveData options:NSJSONReadingMutableContainers error:&error];
    if(error){
        NSLog(@"出现异常%@",error);
    }else{
        NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;
        
        if(httpResponse.statusCode==200){
            NSLog(@"服务器成功响应!>>%@",[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]);
        }else{
            NSLog(@"服务器返回失败>>%@",[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]);
        }
    }
    return data;
}

#pragma mark -- 获取验证码
- (void)startCodeBtnTimeWithBtn:(UIButton *)btn
{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        NSString *title = @"重新发送";
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [btn setAttributedTitle:[TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.33 and:title] forState:UIControlStateNormal];
                btn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout %60 ;
            NSString *name = @"重新发送";
            NSString *strTime = [NSString stringWithFormat:@"%@%d",name,seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
               
                [btn setAttributedTitle:[TTKUtil getAtttributeStringColorWithLineSpace:0 kern:1.33 and:strTime] forState:UIControlStateNormal];
                btn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    
    dispatch_resume(_timer);
}

#pragma mark -- 登录
- (void)loginClick:(UIButton *)btn
{
    //判断是否为空
    if (IsEmptyStr(self.phoneTF.text)) {
        [self ShowHUDWithMessage:@"手机号不能为空"];
        return;
    }
    if (IsEmptyStr(self.codeTF.text)) {
        [self ShowHUDWithMessage:@"验证码不能为空"];
        return;
    }
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    [data setValue:self.phoneTF.text forKey:@"mobile"];
    [data setValue:self.codeTF.text forKey:@"verify_code"];
    [HttpRequest formPostPath:Login params:data resultBlock:^(id Data, MsgModel *msgModel) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (msgModel.status==200) {
                [self ShowHUDWithMessage:@"登录成功"];
                NSDictionary *dict = Data[@"attributes"];
                NSString *shopState = [NSString stringWithFormat:@"%@",dict[@"shopStatusCode"]];
                //保存店铺状态
                USER_DEFAULTS_SAVE(shopState, StoreStatue);
                NSString *result = [NSString stringWithFormat:@"%@",Data[@"result"]];
                USER_DEFAULTS_SAVE(result, LoginStatue);
                
                //设置推送别名
                NSString * alias = [NSString stringWithFormat:@"%@",dict[@"loginUserId"]];
                NSLog(@"设置的别名 %@", alias);
                [JPUSHService setAlias:alias completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                    NSLog(@"别名:%@ seq=%li",iAlias,(long)seq);
                } seq:0];
                if ([shopState intValue] == -404) {
                    //店铺不存在 跳转注册
                    ADDNewShopViewController *addVC = [ADDNewShopViewController new];
                    addVC.mobile = self.phoneTF.text;
                    [self.navigationController pushViewController:addVC animated:YES];
                }
                else if ([shopState integerValue] == -10)
                {
                    ADDNewShopViewController *addNew = [ADDNewShopViewController new];
                    addNew.isFailure = YES;
                    [self.navigationController pushViewController:addNew animated:YES];
                }
                else if ([dict[@"shopStatusCode"]integerValue] == 0 && msgModel.status == 200)
                {
                    USER_DEFAULTS_SAVE(result, LoginStatue);
                    NSString *step = dict[@"shopStatusExtend"][@"step"];
                    //保存step的步骤
                    USER_DEFAULTS_SAVE(step, Step);
                    if (![TTKUtil isNil:step] && ([step integerValue] == 100 || [step integerValue]==105)) {
                        CreateAccountController *createVC = [CreateAccountController new];
                        [self.navigationController pushViewController:createVC animated:YES];
                    }
                    else if (![TTKUtil isNil:step] &&([step integerValue]==110 || [step integerValue]==115 ||[step integerValue]==116))
                    {
                        //申请绑卡
                        MaintainViewController *mainVC = [MaintainViewController new];
                        [self.navigationController pushViewController:mainVC animated:YES];
                    }
                    else if (![TTKUtil isNil:step] &&[step integerValue]==120)
                    {
                        //签约状态
                        BasicWebViewController *basicVC = [BasicWebViewController new];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [HttpRequest formPostPath:GetSignUrl_API params:nil resultBlock:^(id Data, MsgModel *msgModel)
                             {
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                     basicVC.url = Data[@"result"];
                                     [self.navigationController pushViewController:basicVC animated:YES];
                                 });
                             }];
                        });
                    }
                }else if ([dict[@"shopStatusCode"]integerValue] == 10 && msgModel.status == 200)
                {
                    //签约状态
                    CheckShopViewController *check = [CheckShopViewController new];
                    [self.navigationController pushViewController:check animated:YES];
                    
                }else if ([dict[@"shopStatusCode"]integerValue] == 1 &&msgModel.status == 200)
                {
                    //loginUserId
                    //店铺状态正常，进⼊入到⾸首⻚页
                    MYHTabBarController *tab = [MYHTabBarController new];
                    AppDelegate* app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    app.window.rootViewController = tab;
                }else {
                    [self ShowHUDWithMessage:dict[@"shopStatusBizCode"]];
                }
            }
            else
            {
                [TTKUtil hudShowMessage:@"账号或验证码错误"];
            }
        });
    }];
//
//    ADDNewShopViewController *addVC = [ADDNewShopViewController new];
//    [self.navigationController pushViewController:addVC animated:YES];
}
#pragma mark -- 判断店铺状态
- (void)changeShopState
{
    //0 表示正常店铺，10：待审核， 30： 待小程序授权（响应结果中的扩展字段attributes中会放入 auth_url 字段即授权链接）
    
    [[HttpRequest currentHttpRequest]postPath:ShopState_API params:nil resultBlock:^(id Data, MsgModel *msgModel) {
    }];
//    [HttpRequest formPostPath:ShopState_API params:nil resultBlock:^(id Data, MsgModel *msgModel) {
//
//    }];
}

#pragma mark -- 微信登录
- (void)wechatBtnClick:(UIButton *)btn
{
    [self ShowHUDWithMessage:@"待完善"];
}
@end
